package cn.xz.hfsk.activity

import android.content.ContentValues.TAG
import android.os.Handler
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import cn.xz.hfsk.R
import cn.xz.hfsk.adapter.LightCAdapter
import cn.xz.hfsk.adapter.LightTAdapter
import cn.xz.hfsk.base.BaseActivity
import cn.xz.hfsk.base.BaseApplication
import cn.xz.hfsk.bean.AreaList
import cn.xz.hfsk.bean.CommonLib
import cn.xz.hfsk.bean.LightList
import cn.xz.hfsk.bean.LightOpenDean
import cn.xz.hfsk.databinding.ActivityLightBinding
import cn.xz.hfsk.dialog.AllClickDialog
import cn.xz.hfsk.net.ControlDevice
import cn.xz.hfsk.util.*

/**
 * 灯光列表界面
 * */
class LightActivity: BaseActivity<ActivityLightBinding>(R.layout.activity_light) {

    //内容集合
    private val mCList: MutableList<LightList> = arrayListOf()
    //默认所有ID
    private val mID = -999
    //一页显示多少个数据(只能是偶数，否则界面不能平均分)
    private var mNum = 8
    //分组用的集合
    private val myFList: MutableList<LightList> = arrayListOf()
    //列表集合
    private val mList: MutableList<RecyclerView> = arrayListOf()
    //适配器集合
    private val mAdapterList: MutableList<LightCAdapter> = arrayListOf()
    //用来存放圆点
    private var tipList: Array<TextView?> = arrayOfNulls<TextView>(3)
    //获取设备状态
    private var handler: Handler? = null
    //当前显示界面的适配器
    private var mAdapter: LightCAdapter? = null
    //当前查询设备的下标
    private var queryIndex: Int = 0


    override fun initData() {
        //获取灯光数据
        val lightList = SessionUtils.getDataList(CommonLib.Light_CACHE, LightList::class.java)
        //有内容再去设置标题
        if (lightList.isNotEmpty()){
            //获取分类
            val hallList = SessionUtils.getDataList(CommonLib.Hall_CACHE, AreaList::class.java)
            //设置标题，多个标题才显示，只有一个不显示
            if (hallList.isNotEmpty() && hallList.size > 1){
                mDataBind.rvLightTitle.visible()
                //默认添加一个所有
                hallList.add(0,AreaList(mID,"所有灯光", select = true))
                setHall(hallList)
            }else{
                mDataBind.rvLightTitle.invisible()
            }

            mCList.clear()
            mCList.addAll(lightList)
            createLight(mCList)
        }
    }

    override fun initEvent() {
        //一键全开
        mDataBind.tvOpenAll.setOnClickListener {
            AllClickDialog.newInstance(true,object : AllClickDialog.OnClickListener{
                override fun onYes() {
                    //全开全关的时候不进行状态查询，等全开完或者关完再说
                    handler?.removeCallbacks(getStatusAll)
                    ControlDevice.openAllLight(object :ControlDevice.OpenLightListener{
                        override fun over() {
                            //重置
                            queryIndex = 0
                            //实时获取设备状态
                            handler?.post(getStatusAll)
                        }
                    })
                }
                override fun onNo() {
                }
            }).show(this.supportFragmentManager,"AllClickDialog1")
        }
        //一键全关
        mDataBind.tvCloseAll.setOnClickListener {
            AllClickDialog.newInstance(false,object : AllClickDialog.OnClickListener{
                override fun onYes() {
                    //全开全关的时候不进行状态查询，等全开完或者关完再说
                    handler?.removeCallbacks(getStatusAll)
                    ControlDevice.closeAllLight(object :ControlDevice.CloseLightListener{
                        override fun over() {
                            //重置
                            queryIndex = 0
                            //实时获取设备状态
                            handler?.post(getStatusAll)
                        }
                    })
                }
                override fun onNo() {
                }
            }).show(this.supportFragmentManager,"AllClickDialog2")
        }
        //返回
        mDataBind.tvBack.setOnClickListener {
            finish()
        }
    }

    private fun setHall(l: MutableList<AreaList>){
        val ms = LinearLayoutManager(this)
        ms.orientation = LinearLayoutManager.HORIZONTAL // 设置 recyclerview 布局方式为横向布局
        val mAdapter = LightTAdapter()
        mDataBind.rvLightTitle.layoutManager = ms
        mDataBind.rvLightTitle.adapter = mAdapter
        mAdapter.setList(l)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            //更改选中状态
            val mT = adapter.data as MutableList<AreaList>
            mT.forEach {
                it.select = false
            }
            mT[position].select = true
            adapter.notifyDataSetChanged()
            //重置对应数据
            val mData = mT[position]
            if (mData.id == mID){
                //所有灯光
                createLight(mCList)
            }else{
                //单独筛选灯光
                val mNewList: MutableList<LightList> = arrayListOf()
                mCList.forEach {
                    if (it.areaID == mData.id){
                        mNewList.add(it)
                    }
                }
                createLight(mNewList)
            }
        }
    }

    private fun createLight(l: MutableList<LightList>){
        mList.clear()
        mAdapterList.clear()
        //创建分组数据
        for (i in 0 until l.size){
            //循环添加数据
            myFList.add(l[i])
            if (myFList.size == mNum){
                //到达规定数量创建一个列表
                createRecycler(myFList)
                myFList.clear()
            }
        }
        //最后的数据也要作为一个界面
        if (myFList.size > 0) {
            createRecycler(myFList)
        }
        myFList.clear()
        //ViewPager相关
        initViewPage()
    }

    private fun initViewPage() {
        mDataBind.vpList.adapter = MyPagerAdapter(mList)
        mDataBind.vpList.currentItem = 0
        mDataBind.vpList.offscreenPageLimit = 2
        //每次清一下监听，否则会重复监听
        mDataBind.vpList.clearOnPageChangeListeners()
        mDataBind.vpList.addOnPageChangeListener(object :
            ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {}
            override fun onPageSelected(position: Int) {
                setFirst(position)
                //切换时改变小圆点
                selectTitle(position)
            }
            override fun onPageScrollStateChanged(state: Int) {}
        })
        //设置小圆点
        setTitle()
        if (handler == null){
            handler = Handler()
        }
        setFirst(0)
    }

    //消息重置操作
    private fun setFirst(i: Int){
        if (handler != null && mAdapterList.isNotEmpty()){
            //默认当前界面适配器为第一个
            mAdapter = mAdapterList[i]
            //重置
            queryIndex = 0
            handler?.removeCallbacks(getStatusAll)
            //实时获取设备状态
            handler?.post(getStatusAll)
        }
    }

    private fun createRecycler(l: MutableList<LightList>){
        val mRecyclerView = RecyclerView(this)
        val layoutParams = RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.MATCH_PARENT,
            RecyclerView.LayoutParams.MATCH_PARENT
        )
        mRecyclerView.layoutParams = layoutParams


        val ms = object : GridLayoutManager(this, mNum/2) {
            //禁止上下滑动
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRecyclerView.layoutManager = ms

        val mAdapter = LightCAdapter()
        //暂存到集合里面统一处理
        mAdapterList.add(mAdapter)
        mRecyclerView.adapter = mAdapter
        mAdapter.setList(l)
        mList.add(mRecyclerView)
    }

    //ViewPager适配器
    internal class MyPagerAdapter(private val list: MutableList<RecyclerView>) :
        PagerAdapter() {
        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            if (position < list.size){
                container.removeView(list[position])
            }
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            container.addView(list[position])
            return list[position]
        }

        override fun getCount(): Int {
            return list.size
        }

        override fun isViewFromObject(view: View, ob: Any): Boolean {
            return ob === view
        }
    }

    /**
     * 切换小圆点*/
    private fun selectTitle(p: Int){
        mDataBind.llIndex.removeAllViews()
        for (i in tipList.indices) {
            if (i == p) {
                tipList[i]!!.background =
                    ContextCompat.getDrawable(BaseApplication.getContext(),R.drawable.bg_28ddfc_dot)
            } else {
                tipList[i]!!.background =
                    ContextCompat.getDrawable(BaseApplication.getContext(),R.drawable.bg_d8d8d8_dot)
            }
            mDataBind.llIndex.addView(tipList[i])
        }
    }

    /**
     * 设置小圆点
     * */
    private fun setTitle() {
        mDataBind.llIndex.removeAllViews()
        tipList = arrayOfNulls(mList.size)
        if (tipList.size > 1) {
            for (i in tipList.indices) {
                val textView = TextView(this)

                val lp = RelativeLayout.LayoutParams(AppHelper.dp2px(8f), AppHelper.dp2px(8f))
                lp.setMargins(0, 0, AppHelper.dp2px(7f), 0)
                textView.layoutParams = lp

                tipList[i] = textView
                //默认第一张图显示为选中状态
                if (i == 0) {
                    tipList[i]!!.background = ContextCompat.getDrawable(BaseApplication.getContext(), R.drawable.bg_28ddfc_dot)
                } else {
                    tipList[i]!!.background = ContextCompat.getDrawable(BaseApplication.getContext(), R.drawable.bg_d8d8d8_dot)
                }
                mDataBind.llIndex.addView(tipList[i])
            }
        }
    }

    private var getStatusAll: Runnable = object : Runnable {
        override fun run() {
            //当前显示的适配器的数据
            if (mAdapter != null){
                val mGetData = mAdapter?.data!!
                if (mGetData.size > 0) {
                    //获取数据
                    val setTcpData = mGetData[queryIndex]
                    Log.e(TAG, "run: 查询灯光光状态-->" + setTcpData.name )
                    //做对比，相同不发，不相同才发，要不然一直发有问题
                    if (queryIndex > 0){
                        if (mGetData[queryIndex -1].switchGroup != setTcpData.switchGroup ||
                            mGetData[queryIndex -1].com != setTcpData.com ){
                            //发送数据
                            SendTcpUtils.send(setTcpData.switchGroup,setTcpData.com.toInt() - 1,
                                setTcpData.switchIP!!,setTcpData.switchPort!!,object :SendTcpUtils.OnListener{
                                    override fun get(l: ArrayList<LightOpenDean>) {
                                        setDeviceStatus(l)
                                    }
                                })
                        }
                    }else{
                        //发送数据
                        SendTcpUtils.send(setTcpData.switchGroup,setTcpData.com.toInt() - 1,
                            setTcpData.switchIP!!,setTcpData.switchPort,object :SendTcpUtils.OnListener{
                                override fun get(l: ArrayList<LightOpenDean>) {
                                    setDeviceStatus(l)
                                }
                            })
                    }
                    //平时800毫秒一次
                    handler?.postDelayed(this, 800)
                    queryIndex++
                    //到达固定长度之后五秒重发
                    if (queryIndex == mGetData.size) {
                        handler?.removeCallbacks(this)
                        queryIndex = 0
                        handler?.postDelayed(this, 30 * 1000)
                    }
                } else {
                    handler?.removeCallbacks(this)
                    queryIndex = 0
                }
            }
        }
    }

    //动态更换设备状态
    private fun setDeviceStatus(l: ArrayList<LightOpenDean>){
        if (l.isNotEmpty()){
            if (mAdapter != null){
                try {
                    val mBean = mAdapter!!.data
                    for (i in 0 until mBean.size){
                        l.forEach {
                            //根据下标去判断当前条目状态是否改变，改变了才更新状态
                            if (it.com == (mBean[i].com.toInt() - 1) &&
                                it.switchGroup == mBean[i].switchGroup &&
                                it.switchIndex == mBean[i].switchIndex &&
                                it.opening != mBean[i].opening){
                                mBean[i].opening = it.opening
                                runOnUiThread {
                                    mAdapter!!.notifyItemChanged(i)
                                }
                            }
                        }
                    }

                }catch (e: Exception){
                    e.printStackTrace()
                    runOnUiThread {
                        mAdapter!!.notifyDataSetChanged()
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //及时置空
        if (handler != null){
            handler?.removeCallbacks(getStatusAll)
            handler = null
        }
    }
}